package com.fanhang.samples.spring.sql2o.dao.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.fanhang.samples.spring.sql2o.common.Sql2oDaoSupport;
import com.fanhang.samples.spring.sql2o.dao.UserDao;
import com.fanhang.samples.spring.sql2o.po.User;

import static com.google.common.collect.ImmutableMap.*;

@Repository
public class UserDaoImpl extends Sql2oDaoSupport implements UserDao {
	
	@Override
	public User get(Long id) throws Exception {
		String sql = "SELECT id as id,login_name as loginName,password as password,user_name as userName,role_id as roleId,status as status,creator as creator,create_time as createTime FROM stat_user WHERE id = :id";
		return super.getSessionTemplate().fetchFirst(sql, of("id", id), User.class);
	}
	
	@Override
	public List<User> getList(User model) throws Exception {
		StringBuilder sql = new StringBuilder();
		sql.append(" SELECT u.*, \n")
		.append(" r.id 'role.id', \n")
		.append(" r.name 'role.name' \n")
		.append(" FROM stat_user u,stat_role r \n")
		.append(" WHERE u.role_id = r.id \n");
		if (model.getRoleId() != null) {
			sql.append(" and role_id = :roleId ");
		}
		if (model.getCreator() != null) {
			sql.append(" and creator = :creator ");
		}
		if (!StringUtils.isEmpty(model.getUserName())) {
			sql.append(" and user_name like '%:userName%' ");
		}
		return super.getSessionTemplate().fetch(sql, describe(model), User.class);
	}
	

	@Override
	public int save(User model) throws Exception {
		StringBuilder sql = new StringBuilder(" insert into stat_user(id,login_name,password,user_name,role_id,status,creator,create_time) ");
		sql.append(" values (:id, :loginName, :password, :userName, :roleId, :status, :creator, :createTime) ");
		return super.getSessionTemplate().update(sql, describe(model));
	}

	@Override
	public int delete(User model) throws Exception {
		String sql = "update employee set name=:name,birthday=:birthday,status=:status WHERE id = :id";
		return super.getSessionTemplate().update(sql, describe(model));
	}

	@Override
	public int update(User model) throws Exception {
		String sql = "update employee set name=:name,birthday=:birthday,status=:status WHERE id = :id";
		return super.getSessionTemplate().update(sql, describe(model));
	}
}
